import torch
from torch import nn


# 基本计算单元
class VGGBlock(nn.Module):
    def __init__(self, in_channels, middle_channels, out_channels):
        super().__init__()
        self.relu = nn.ReLU(inplace=True)
        self.conv1 = nn.Conv2d(in_channels, middle_channels, 3, padding=1)
        self.bn1 = nn.BatchNorm2d(middle_channels)
        self.conv2 = nn.Conv2d(middle_channels, out_channels, 3, padding=1)
        self.bn2 = nn.BatchNorm2d(out_channels)

    def forward(self, x):
        # VGGBlock实际上就是相当于做了两次卷积
        out = self.conv1(x)
        out = self.bn1(out)  # 归一化
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        return out


class UNet_ConvTranspose2d(nn.Module):
    def __init__(self, num_classes, input_channels=3, **kwargs):
        super().__init__()

        nb_filter = [64, 128, 256, 512, 1024]

        self.pool = nn.MaxPool2d(2, 2)

        # 编码器部分
        self.conv0_0 = VGGBlock(input_channels, nb_filter[0], nb_filter[0])
        self.conv1_0 = VGGBlock(nb_filter[0], nb_filter[1], nb_filter[1])
        self.conv2_0 = VGGBlock(nb_filter[1], nb_filter[2], nb_filter[2])
        self.conv3_0 = VGGBlock(nb_filter[2], nb_filter[3], nb_filter[3])
        self.conv4_0 = VGGBlock(nb_filter[3], nb_filter[4], nb_filter[4])

        # 解码器部分，使用 ConvTranspose2d 进行上采样
        self.up4 = nn.ConvTranspose2d(nb_filter[4], nb_filter[3], kernel_size=2, stride=2)
        self.conv3_1 = VGGBlock(nb_filter[3] * 2, nb_filter[3], nb_filter[3])

        self.up3 = nn.ConvTranspose2d(nb_filter[3], nb_filter[2], kernel_size=2, stride=2)
        self.conv2_2 = VGGBlock(nb_filter[2] * 2, nb_filter[2], nb_filter[2])

        self.up2 = nn.ConvTranspose2d(nb_filter[2], nb_filter[1], kernel_size=2, stride=2)
        self.conv1_3 = VGGBlock(nb_filter[1] * 2, nb_filter[1], nb_filter[1])

        self.up1 = nn.ConvTranspose2d(nb_filter[1], nb_filter[0], kernel_size=2, stride=2)
        self.conv0_4 = VGGBlock(nb_filter[0] * 2, nb_filter[0], nb_filter[0])

        self.final = nn.Conv2d(nb_filter[0], num_classes, kernel_size=1)

    def forward(self, input):
        # 编码器路径
        x0_0 = self.conv0_0(input)  # [N, 32, H, W]
        x1_0 = self.conv1_0(self.pool(x0_0))  # [N, 64, H/2, W/2]
        x2_0 = self.conv2_0(self.pool(x1_0))  # [N, 128, H/4, W/4]
        x3_0 = self.conv3_0(self.pool(x2_0))  # [N, 256, H/8, W/8]
        x4_0 = self.conv4_0(self.pool(x3_0))  # [N, 512, H/16, W/16]

        # 解码器路径
        x4_0_up = self.up4(x4_0)  # 上采样至 [N, 256, H/8, W/8]
        x3_1 = self.conv3_1(torch.cat([x3_0, x4_0_up], 1))  # 拼接后通道数为 512

        x3_1_up = self.up3(x3_1)  # 上采样至 [N, 128, H/4, W/4]
        x2_2 = self.conv2_2(torch.cat([x2_0, x3_1_up], 1))  # 拼接后通道数为 256

        x2_2_up = self.up2(x2_2)  # 上采样至 [N, 64, H/2, W/2]
        x1_3 = self.conv1_3(torch.cat([x1_0, x2_2_up], 1))  # 拼接后通道数为 128

        x1_3_up = self.up1(x1_3)  # 上采样至 [N, 32, H, W]
        x0_4 = self.conv0_4(torch.cat([x0_0, x1_3_up], 1))  # 拼接后通道数为 64

        output = self.final(x0_4)  # 最终输出 [N, num_classes, H, W]
        return nn.Sigmoid()(output)


# 测试代码：实例化模型并测试其前向传播
if __name__ == "__main__":
    model = UNet_ConvTranspose2d(in_channels=3, num_classes=1)  # 创建 U-Net 模型，输入3通道（RGB），输出1通道（灰度或二分类）
    x = torch.randn((1, 3, 256, 256))  # 创建一个随机输入张量，模拟1张 256x256 的3通道图像
    preds = model(x)  # 执行前向传播
    print(preds.shape)  # 输出张量的尺寸，应该是 (1, 1, 256, 256)，与输入的空间尺寸一致，通道数为1
